package cli.command;

import cli.view.Formats;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.text.Format;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

public class ShowStatus implements Command {
    private PrintWriter out;
    private Path currentPath;

    public ShowStatus(PrintWriter out, Path currentPath) {
        this.out = out;
        this.currentPath = currentPath;
    }

    @Override
    public void handle(String[] args) {
        int pos = 0;
        if (pos >= args.length) {
            out.println("请输入路径！");
            return;
        }
        Path path;
        try {
            path = currentPath.resolve(args[pos]);
        } catch (InvalidPathException e) {
            out.println("无法识别路径"+args[pos]+"！");
            return;
        }
        pos++;
        if (pos < args.length) {
            out.println("无法识别参数"+args[pos]+"!");
            return;
        }
        try {
            StringBuffer sb = new StringBuffer();
            if (Files.isRegularFile(path)) {
                sb.append("类型：").append("文件").append('\n');
                sb.append("大小：").append(Formats.memorySize(Files.size(path))).append("\n");
            } else if (Files.isDirectory(path)) {
                sb.append("类型：").append("文件夹").append('\n');
                final long[] size = {0};
                final int[] num = {0};
                Files.walk(path).forEach(p -> {
                    num[0]++;
                    try {
                        size[0] += Files.size(p);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
                sb.append("大小：").append(Formats.memorySize(size[0])).append('\n');
                sb.append("文件数目：").append(num[0]).append('\n');
            } else {
                sb.append("类型：").append("？？？").append('\n');
            }
            sb.append("权限：").append(Files.isReadable(path)? "r" : "-").append(Files.isWritable(path)? "w" : "-").append(Files.isExecutable(path)? "x" : "-").append("\n");
            sb.append("拥有者：").append(Files.getOwner(path)).append("\n");
            sb.append("修改时间：").append(LocalDateTime.ofInstant(Files.getLastModifiedTime(path).toInstant(), ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"))).append("\n");
            out.printf(sb.toString());
        } catch (IOException e) {
            out.println("查询属性失败！");
        }
    }
}
